package com.yuanian.ecsplus.converter;

import com.yuanian.ecsplus.exception.EcsPlusException;
import com.yuanian.ecsplus.context.ReflectContext;

/**
 * boolean类型的转换器
 */
public class BooleanTypeConverter implements TypeConverter {

    @Override
    public Object obj2Map(ReflectContext reflectContext) {
        if (reflectContext.getObject() == null || reflectContext.getField() == null) {
            return null;
        }
        try {
            Object result = reflectContext.getRawResult();
            //pDeleted数据放入的varchar,但是实体类为boolean
            if (reflectContext.getField().getName().equals("pDeleted") && result != null) {
                boolean flag = (Boolean)result;
                return flag ? "TRUE" : "FALSE";
            } else {
                return result;
            }
        } catch (IllegalAccessException e) {
            throw new EcsPlusException(e.getCause());
        }
    }

    @Override
    public Object map2Obj(ReflectContext reflectContext) {
        if (reflectContext.getMap() == null || reflectContext.getField() == null) {
            return null;
        }
        //获取MAP对应字段的数据
        Object propData = reflectContext.getMapData();
        if (propData == null) {
            return null;
        } else if (propData instanceof String) {
            //FALSE false 0 --> false
            return !isFalse((String)propData);
        } else {
            return propData instanceof Boolean ? propData : null;
        }
    }

    /**
     * 字符串是否为false
     * @param str
     * @return
     */
    private boolean isFalse(String str) {
        String upperCaseStr = str.toUpperCase();
        return upperCaseStr.equals("FALSE") || upperCaseStr.equals("0");
    }

}
